<template>
  <a-drawer
    :open="historyModel"
    width="1082"
    title="消费记录"
    :maskClosable="false"
    placement="right"
    @close="cancelDrawer"
  >
    <div class="history-cls">
      <a-row class="member-info">
        <a-col>姓名：{{ actionItem.vipName }}</a-col>
        <a-col :offset="1">手机号: {{ actionItem.vipMobile }}</a-col>
        <a-col :offset="1">充值日期: {{ actionItem.rechargeDate }}</a-col>
      </a-row>
      <a-table
        :dataSource="dataSource"
        :columns="columns"
        :loading="pageLoading"
        :pagination="false"
      >
        <template #emptyText>
          <empty />
        </template>
        <template #bodyCell="{ column, record, index }">
          <template v-if="!editFlagList[index]">
            <template v-if="column.key === 'consumeTime'">
              {{ record.consumeTime }}
            </template>
            <template v-else-if="column.key === 'consumeType'">
              {{ record.consumeType === 'SITE_ORDER' ? '订场' : '其他' }}
            </template>
            <template v-else-if="column.key === 'consumeHours'">
              {{ record.consumeType === 'SITE_ORDER' ? `${record.consumeHours}小时` : '-' }}
            </template>
            <template v-else-if="column.key === 'setting'">
              <div class="action-cls">
                <a-button size="small" @click="handleAddOrUpdateMember(index, record)"
                  >编辑</a-button
                >
                <a-popconfirm
                  :title="`确定删除该消费记录？`"
                  placement="left"
                  @confirm="handleDelete(record.id)"
                >
                  <template #icon><QuestionCircleOutlined style="color: red" /></template>
                  <a-button size="small" type="primary" danger ghost>删除</a-button>
                </a-popconfirm>
              </div>
            </template>
            <template v-else>
              {{ record[column.key] || '-' }}
            </template>
          </template>
          <template v-else>
            <template v-if="column.key === 'consumeTime'">
              <a-date-picker
                v-model:value="consumptionForm.consumeTime"
                class="input-01"
                show-time
                :allowClear="false"
              />
            </template>
            <template v-else-if="column.key === 'consumeType'">
              <a-radio-group
                v-model:value="consumptionForm.consumeType"
                name="radioGroup"
                @change="handleConsumeTypeChange"
              >
                <a-radio value="SITE_ORDER">订场</a-radio>
                <a-radio value="OTHER_ORDER">其他</a-radio>
              </a-radio-group>
            </template>
            <template v-else-if="column.key === 'consumeHours'">
              <a-input-number
                v-if="consumptionForm.consumeType === 'SITE_ORDER'"
                v-model:value="consumptionForm.consumeHours"
                addon-after="小时"
                :min="0.1"
                :precision="1"
              />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'unitPrice'">
              <a-input-number
                v-model:value="consumptionForm.unitPrice"
                addon-after="¥"
                :min="0.1"
                :precision="2"
              />
            </template>
            <template v-else-if="column.key === 'consumeTotalMoney'"> - </template>
            <template v-else-if="column.key === 'setting'">
              <div class="action-cls">
                <a-button size="small" type="primary" @click="handleSaveEdit" :loading="editLoading"
                  >保存</a-button
                >
                <a-button size="small" @click="handleCancelEdit">取消</a-button>
              </div>
            </template>
            <template v-else>
              {{ record[column.key] || '-' }}
            </template>
          </template>
        </template>
      </a-table>
    </div>
  </a-drawer>
</template>
<script setup lang="ts" name="MemberCreate">
import { Empty, message } from 'ant-design-vue'
import { computed, reactive, ref, watch, type Ref, type UnwrapRef } from 'vue'
import dayjs from 'dayjs'
import type { ConsumptionForm, ConsumptionItem, TableItem } from '#/member-management'
import {
  addOrUpdateMemberConsumption,
  deleteConsumptionById,
  getMemberConsumptionById
} from '@/api/member-management'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
const emit = defineEmits(['update:historyModel', 'getList'])
const props = defineProps({
  historyModel: {
    type: Boolean,
    default: false
  },
  actionItem: {
    type: Object,
    default: () => {}
  }
})
const historyModel = computed(() => props.historyModel)
const actionItem = computed(() => props.actionItem as TableItem)

const pageLoading = ref(false)
const dataSource: Ref<ConsumptionItem[]> = ref([])
const dataSourceBackup: Ref<ConsumptionItem[]> = ref([])

const columns = [
  {
    title: '消费时间',
    dataIndex: 'consumeTime',
    key: 'consumeTime',
    width: 200,
    ellipsis: true
  },
  {
    title: '消费类型',
    dataIndex: 'consumeType',
    key: 'consumeType',
    width: 160,
    ellipsis: true
  },
  {
    title: '消费时长',
    dataIndex: 'consumeHours',
    key: 'consumeHours',
    width: 120,
    ellipsis: true
  },
  {
    title: '单价(¥)',
    dataIndex: 'unitPrice',
    key: 'unitPrice',
    width: 120,
    ellipsis: true
  },
  {
    title: '总费用(¥)',
    dataIndex: 'consumeTotalMoney',
    key: 'consumeTotalMoney',
    width: 120,
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'setting',
    key: 'setting',
    width: 150
  }
]
const getList = () => {
  pageLoading.value = true
  getMemberConsumptionById(actionItem.value.id)
    .then((res) => {
      dataSourceBackup.value = res.data
      dataSource.value = res.data
      pageLoading.value = false
    })
    .catch(() => {
      pageLoading.value = false
    })
}

const handleDelete = (id: number) => {
  deleteConsumptionById(id).then(() => {
    message.success('删除消费记录成功')
    getList()
    emit('getList')
  })
}

const cancelDrawer = () => {
  editFlagList.value = []
  emit('update:historyModel', false)
}

const editFlagList: Ref<boolean[]> = ref([])
const editLoading = ref(false)
const consumptionForm: UnwrapRef<ConsumptionForm> = reactive({
  id: 0,
  vipId: 0,
  consumeTime: dayjs(),
  consumeType: 'SITE_ORDER',
  consumeHours: undefined,
  unitPrice: undefined
})
const handleAddOrUpdateMember = (index: number, record: ConsumptionItem) => {
  const findEdit = editFlagList.value.filter((a) => a).length
  if (findEdit) {
    message.warning('操作失败: 一次仅允许编辑一行数据！')
  } else {
    dataSource.value = [...dataSourceBackup.value]
    editFlagList.value[index] = true
    consumptionForm.id = record.id
    consumptionForm.vipId = record.vipId
    consumptionForm.consumeTime = dayjs(record.consumeTime)
    consumptionForm.consumeType = record.consumeType
    consumptionForm.consumeHours = record.consumeHours
    consumptionForm.unitPrice = record.unitPrice
  }
}

const handleCancelEdit = () => {
  message.info('取消保存！')
  dataSource.value = [...dataSourceBackup.value]
  editFlagList.value = []
}

const handleConsumeTypeChange = () => {
  if (consumptionForm.consumeType === 'OTHER_ORDER') {
    consumptionForm.consumeHours = 1
  }
}

const handleSaveEdit = () => {
  if (!consumptionForm.consumeHours) {
    message.error('保存失败：消费时长不允许为空')
    return
  }
  if (!consumptionForm.unitPrice) {
    message.error('保存失败：单价不允许为空')
    return
  }
  editLoading.value = true
  addOrUpdateMemberConsumption(consumptionForm)
    .then(() => {
      message.success('会员消费记录保存成功！')
      getList()
      editFlagList.value = []
      editLoading.value = false
      emit('getList')
    })
    .catch(() => {
      editLoading.value = false
    })
}

watch(
  () => props.historyModel,
  (val) => {
    if (val) getList()
  }
)
</script>
<style lang="less" scoped>
.input-01 {
  width: 180px;
}
.history-cls {
  padding: 20px;
  width: 100%;
  height: 100%;
  .member-info {
    height: 50px;
  }
  .action-cls {
    button {
      margin-right: 16px;
    }
  }
}
</style>
